import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { useGlobSetting } from '/@/hooks/setting';
import { forIn, isNil } from 'lodash-es';

const { createMessage } = useMessage();
useGlobSetting();
/**
 * 导出文件xlsx的mime-type
 */
export const XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
/**
 * 导出文件xlsx的文件后缀
 */
export const XLSX_FILE_SUFFIX = '.xlsx';

export function useMethods() {
  /**
   * 导出xls
   * @param name
   * @param url
   */
  async function exportXls(name, url, params, isXlsx = false) {
    const data = await defHttp.post({ url: url, params: params, responseType: 'blob', timeout: 60 * 1000 }, { isTransformResponse: false });
    if (!data) {
      createMessage.warning('文件下载失败');
      return;
    }
    if (!name || typeof name != 'string') {
      name = '导出文件';
    }
    const blobOptions = { type: 'application/vnd.ms-excel' };
    let fileSuffix = '.xls';
    if (isXlsx === true) {
      blobOptions['type'] = XLSX_MIME_TYPE;
      fileSuffix = XLSX_FILE_SUFFIX;
    }
    //@ts-ignore
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      //@ts-ignore
      window.navigator.msSaveBlob(new Blob([data], blobOptions), name + fileSuffix);
    } else {
      const url = window.URL.createObjectURL(new Blob([data], blobOptions));
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', name + fileSuffix);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); //下载完成移除元素
      window.URL.revokeObjectURL(url); //释放掉blob对象
    }
  }

  /**
   * 导入xls
   * @param data 导入的数据
   * @param url
   * @param success 成功后的回调
   */
  async function importXls(data, url, success, params) {
    const form = new FormData();
    form.append(data.filename, data.file);
    //await defHttp.postFormFile(url, form, { success: isReturn });
    if (!isNil(params)) {
      forIn(params, (value, key) => {
        form.append(key, value);
      });
    }

    return defHttp
      .postFormFile(url, form)
      .then((res) => {
        // isReturn(res);
        typeof success === 'function' ? success(res) : '';
        return Promise.resolve(res);
      })
      .catch((res) => {
        return Promise.reject(res);
      });
  }

  return {
    handleExportXls: (name: string, url: string, params?: object) => exportXls(name, url, params),
    handleImportXls: (data, url, success, params?: object) => importXls(data, url, success, params),
    handleExportXlsx: (name: string, url: string, params?: object) => exportXls(name, url, params, true),
    handleUploadFile: (data, url, success, params?: object) => importXls(data, url, success, params),
  };
}
